﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.T.BasicData.Infraeturcture
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly ILogger<BaseRepository<T>> logger;
        private readonly MyDbContext ctx;

        public BaseRepository(ILogger<BaseRepository<T>> logger,MyDbContext ctx)
        {
            this.logger = logger;
            this.ctx = ctx;
        }
        public async Task<int> AddAnyx(T t)
        {
            try
            {
                await ctx.Set<T>().AddAsync(t);
                return await ctx.SaveChangesAsync();

            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        public IQueryable<T> Getlist()
        {
            try
            {
                return ctx.Set<T>().AsQueryable();
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        public async Task<T> GetValue(Expression<Func<T, bool>> exp)
        {
            try
            {
                return await ctx.Set<T>().Where(exp).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        public async Task<int> Update(T t)
        {
            try
            {
                ctx.Set<T>().Update(t);
                return await ctx.SaveChangesAsync();
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
    }
}
